/*
 * Copyright (C) 2021 Huawei Device Co., Ltd.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package com.xuexiang.xuidemo.slice;

import com.xuexiang.xui_lib.util.LogUtils;

import ohos.aafwk.ability.AbilitySlice;
import ohos.aafwk.content.Intent;
import ohos.aafwk.content.Operation;
import ohos.agp.components.Component;
import ohos.agp.components.DependentLayout;
import ohos.agp.components.DirectionalLayout;
import ohos.agp.components.Image;
import ohos.agp.components.ListContainer;
import ohos.agp.components.Text;
import ohos.agp.components.TextField;
import ohos.agp.components.element.Element;
import ohos.agp.components.element.ElementScatter;
import ohos.app.Context;
import ohos.multimodalinput.event.KeyEvent;

import com.xuexiang.xui_lib.util.UntilTNT;
import com.xuexiang.xui_lib.util.ViewModel;
import com.xuexiang.xuidemo.MyApplication;
import com.xuexiang.xuidemo.ResourceTable;
import com.xuexiang.xuidemo.db.DBService;
import com.xuexiang.xuidemo.db.SearchRecord;
import com.xuexiang.xuidemo.provider.SetterProvider;
import com.xuexiang.xuidemo.util.DbUntil;
import com.xuexiang.xuidemo.view.DistributionData;

import java.util.ArrayList;
import java.util.List;

/**
 * 标题栏的搜索框
 *
 * @since 2021-03-19
 */
public class SearchAbilitysice extends AbilitySlice implements Component.ClickedListener {
    private Image imgabout;
    private Image imgseart;
    private Image imghit;
    private Image imgclear;
    private Image imgCrosssign;
    private TextField textfield;
    private DependentLayout detlayout;
    private DependentLayout dedtlat;
    private Context context;
    private String data;
    private boolean isOne = true;
    private DistributionData testdata;
    private DirectionalLayout wholeLayout; // 显示按钮控件的显示框list_container
    private ListContainer listcontainer;
    private SetterProvider setterProvider;
    private String[] arraydata = null;
    private List<UntilTNT> list;
    private AbilitySlice abilitySlice;
    private DBService dbService;
    private List<SearchRecord> listdb = null;
    private final int itempicture = ResourceTable.Media_icon_error;
    private final int anInt1024 = 1024;

    /**
     * 加载页面
     *
     * @param intent
     */
    public void onStart(Intent intent) {
        super.onStart(intent);
        super.setUIContent(ResourceTable.Layout_searchslice_layout);
        dbService = DbUntil.getDbService();
        listdb = dbService.queryAll(); // 查询数据
        context = this;
        abilitySlice = this;
        list = new ArrayList<>();
        ViewModel viewModel = new ViewModel(this);
        arraydata = viewModel.getStringResource(ResourceTable.Strarray_serch_array);
        initview();
        initdata();
        initviewdata();
        initKeyEvent();
        if (listdb == null) {
            LogUtils.info("SearchAbilitysice", "空的");
        } else {
            for (int i = 0; i < listdb.size(); i++) {
                testdata.setCompoentText(listdb.get(i).getContent());
            }
        }
        listdb = null;
    }

    private void initview() {
        listcontainer = (ListContainer) findComponentById(ResourceTable.Id_list_container);
        setterProvider = new SetterProvider(list, this);
        listcontainer.setItemProvider(setterProvider);

        wholeLayout = (DirectionalLayout) findComponentById(ResourceTable.Id_WholeLayout);
        testdata = (DistributionData) findComponentById(ResourceTable.Id_testdata);
        imgabout = (Image) findComponentById(ResourceTable.Id_imgabout);
        imgseart = (Image) findComponentById(ResourceTable.Id_imgseart);
        imghit = (Image) findComponentById(ResourceTable.Id_imghit);
        imgclear = (Image) findComponentById(ResourceTable.Id_imgclear);
        imgCrosssign = (Image) findComponentById(ResourceTable.Id_imgCrosssign);
        textfield = (TextField) findComponentById(ResourceTable.Id_Textfield);
        detlayout = (DependentLayout) findComponentById(ResourceTable.Id_Detlayout);
        dedtlat = (DependentLayout) findComponentById(ResourceTable.Id_Dedtlat);
        imgabout.setClickedListener(this::onClick);
        imgseart.setClickedListener(this::onClick);
        imghit.setClickedListener(this::onClick);
        imgclear.setClickedListener(this::onClick);
        imgCrosssign.setClickedListener(this::onClick);
    }

    private void initdata() {
        listcontainer.setItemClickedListener((container, component, position, id) -> {
            UntilTNT item = (UntilTNT) listcontainer.getItemProvider().getItem(position);
            imgCrosssign.setVisibility(Component.HIDE);
            for (int i = 1; i < testdata.getLaoutid(); i++) {
                testdata.removeComponentById(i);
            }
            testdata.setInt(anInt1024, 1); // testdata.LaoutID = 1;testdata.ysckj = 1024;
            listdb = dbService.queryAll();
            if (listdb.isEmpty()) { // 判断list是否为空
                SearchRecord record = new SearchRecord();
                record.setContent(item.getName());
                record.setTime(System.currentTimeMillis()); // 获取时间轴
                dbService.insert(record);
            } else {
                for (int i = 0; i < listdb.size(); i++) {
                    if (listdb.get(i).getContent().equals(item.getName())) {
                        LogUtils.info(this.getBundleName(), item.getName());
                    } else {
                        SearchRecord record = new SearchRecord();
                        record.setContent(item.getName());
                        record.setTime(System.currentTimeMillis()); // 获取时间轴
                        dbService.insert(record);
                    }
                }
            }
            listdb = dbService.queryAll();
            for (int i = 0; i < listdb.size(); i++) {
                LogUtils.info("SearchAbilitysice==点击事件的长度", list.size() + "长度");
                testdata.setCompoentText(listdb.get(i).getContent());
            }

            detlayout.setVisibility(Component.HIDE); // 导航栏出现
            dedtlat.setVisibility(Component.VISIBLE); // 搜索框消失
            Element element = ElementScatter.getInstance(context)
                .parse(ResourceTable.Graphic_backfroud_search);
            wholeLayout.setBackground(element); // 设置显示页的背景
            list.clear(); // 重新加载,是为了删除的list数据不在站位置
            setterProvider = new SetterProvider(list, abilitySlice);
            listcontainer.setItemProvider(setterProvider);
            listcontainer.setVisibility(Component.HIDE);

            for (int j = 0; j < arraydata.length; j++) {
                if (arraydata[j].equals(data)) { // 存在相应的组件
                    startability("com.xuexiang.xuidemo.ability.TitleBarAbility");
                    break;
                }
            }
        });
    }

    private void initviewdata() {
        textfield.addTextObserver(new Text.TextObserver() {
            @Override
            public void onTextUpdated(String string, int i, int i1, int i2) {
                LogUtils.info("SearchAbilitysice-字体动态监听", string);
                imgCrosssign.setVisibility(Component.VISIBLE);
                data = string;
                isOne = true;
                if (string.length() > 0) {
                    listcontainer.setVisibility(Component.VISIBLE);
                    for (int j = 0; j < arraydata.length; j++) {
                        if (arraydata[j].contains(string)) {
                            LogUtils.info("SearchAbilitysice-包含", arraydata[j]);
                            UntilTNT until = new UntilTNT();
                            until.setPicture(itempicture);
                            until.setName(arraydata[j]);
                            list.add(until);
                        }
                    }
                    setterProvider.notifyDataChanged();
                }
            }
        });

        textfield.addTextObserver(new Text.TextObserver() {
            @Override
            public void onTextUpdated(String string, int i, int i1, int i2) {
                LogUtils.info("SearchAbilitysice-字体动态监听", string);
                imgCrosssign.setVisibility(Component.VISIBLE);
                data = string;
                isOne = true;
                if (string.length() > 0) {
                    listcontainer.setVisibility(Component.VISIBLE);
                    for (int j = 0; j < arraydata.length; j++) {
                        if (arraydata[j].contains(string)) { // 判断数组中是否有这个字符
                            LogUtils.info("SearchAbilitysice-包含", arraydata[j]);
                            UntilTNT until = new UntilTNT();
                            until.setPicture(itempicture);
                            until.setName(arraydata[j]);
                            list.add(until);
                        }
                    }
                    setterProvider.notifyDataChanged();
                }
            }
        });
    }

    private void initKeyEvent() {
        textfield.setKeyEventListener(new Component.KeyEventListener() { // 键盘上的确定事件
            @Override
            public boolean onKeyEvent(Component component, KeyEvent keyEvent) {
                if (keyEvent.getKeyCode() == KeyEvent.KEY_SEARCH
                    || keyEvent.getKeyCode() == KeyEvent.KEY_ENTER) {
                    LogUtils.info("SearchAbilitysice", "键盘的确定按钮");
                    if (isOne) {
                        isOne = false;
                        imgCrosssign.setVisibility(Component.HIDE);
                        detlayout.setVisibility(Component.HIDE); // 导航栏出现
                        dedtlat.setVisibility(Component.VISIBLE); // 搜索框消失
                        Element element = ElementScatter.getInstance(context)
                            .parse(ResourceTable.Graphic_backfroud_search);
                        wholeLayout.setBackground(element);
                        for (int j = 0; j < arraydata.length; j++) {
                            if (arraydata[j].equals(data)) { // 是否和数组的一致
                                startability("com.xuexiang.xuidemo.ability.TitleBarAbility");
                                break;
                            }
                        }
                        list.clear(); // 重新加载,是为了删除的数据
                        setterProvider = new SetterProvider(list, abilitySlice);
                        listcontainer.setItemProvider(setterProvider);
                        listcontainer.setVisibility(Component.HIDE);
                        for (int i = 1; i < testdata.getLaoutid(); i++) {
                            testdata.removeComponentById(i);
                        }
                        testdata.setInt(anInt1024, 1);
                        listdb = dbService.queryAll();
                        setisboole();
                    }
                }
                return false;
            }
        });
    }

    private void setisboole() {
        if (listdb.isEmpty()) { // 判断list是否为空
            SearchRecord record = new SearchRecord();
            record.setContent(data);
            record.setTime(System.currentTimeMillis()); // 获取时间轴
            dbService.insert(record);
        } else {
            for (int i = 0; i < listdb.size(); i++) {
                String arraydt = listdb.get(i).getContent();
                if (arraydt.equals(data)) {
                    LogUtils.info("SearchAbilitysice-获取到一样的数据:", data);
                } else {
                    SearchRecord record = new SearchRecord();
                    record.setContent(data);
                    record.setTime(System.currentTimeMillis()); // 获取时间轴
                    dbService.insert(record);
                }
            }
        }
        listdb = dbService.queryAll(); // 查询数据库
        for (int i = 0; i < listdb.size(); i++) {
            testdata.setCompoentText(listdb.get(i).getContent());
        }
    }

    @Override
    public void onActive() {
        super.onActive();
    }

    @Override
    public void onForeground(Intent intent) {
        super.onForeground(intent);
    }

    @Override
    public void onClick(Component component) {
        switch (component.getId()) {
            case ResourceTable.Id_imgCrosssign:
                listcontainer.setVisibility(Component.HIDE);
                textfield.setText("");
                imgCrosssign.setVisibility(Component.HIDE);
                break;
            case ResourceTable.Id_imgclear:
                dbService.deleteAll(); // 删除数据库所有数据
                testdata.removeAllComponents();
                for (int i = 1; i < testdata.getLaoutid(); i++) {
                    testdata.removeComponentById(i);
                }
                testdata.setInt(anInt1024, 1);
                break;
            case ResourceTable.Id_imgabout:
                terminateAbility();
                break;
            case ResourceTable.Id_imgseart:
                textfield.setText("");
                Element touchedBackGround = ElementScatter.getInstance(context)
                    .parse(ResourceTable.Graphic_background_page1);
                wholeLayout.setBackground(touchedBackGround);
                detlayout.setVisibility(Component.VISIBLE); // 搜索框出现
                dedtlat.setVisibility(Component.HIDE); // 导航栏消失
                break;
            case ResourceTable.Id_imghit: // 箭头
                Element element = ElementScatter.getInstance(context)
                    .parse(ResourceTable.Graphic_backfroud_search);
                wholeLayout.setBackground(element);

                textfield.setText("");
                detlayout.setVisibility(Component.HIDE); // 导航栏出现
                dedtlat.setVisibility(Component.VISIBLE); // 搜索框消失
                list.clear();
                setterProvider = new SetterProvider(list, this);
                listcontainer.setItemProvider(setterProvider);
                listcontainer.setVisibility(Component.HIDE);
                break;
            default:
                break;
        }
    }

    private void startability(String abilityurl) {
        Intent secondIntent = new Intent();
        Operation operation = new Intent.OperationBuilder()
            .withDeviceId("")
            .withBundleName("com.xuexiang.xuidemo")
            .withAbilityName(abilityurl)
            .build();
        secondIntent.setOperation(operation);
        startAbility(secondIntent);
    }
}
